﻿using SqlSugar;
using Digitalmes.Domain.Repositories;

namespace Digitalmes.Infrastructure.Data;

/// <summary>
/// 工作单元管理者。
/// </summary>
internal sealed class UnitOfWorkManager : IUnitOfWorkManage
{
    private readonly ISqlSugarClient _sugarClinet;
    private SugarUnitOfWork? _unitOfWork;

    public UnitOfWorkManager(ISqlSugarClient sqlSugarClient)
    {
        _sugarClinet = sqlSugarClient;
    }

    public IUnitOfWork CreateUow()
    {
        _unitOfWork = _sugarClinet.CreateContext(_sugarClinet.Ado.IsNoTran());
        return new UnitOfWork(_unitOfWork);
    }

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    /// <remarks>注意：在同一事务中，获取的仓储对象进行数据操作时不能并行运行。</remarks>
    public IRepository<T> GetRepository<T>() where T : class, IEntity, new()
    {
        Guard.Against.Null(_unitOfWork, nameof(SugarUnitOfWork));

        //return new SqlSugarRepository<T>(_unitOfWork.Db); // 带作用域
        return new SqlSugarRepositoryWrapper<T>(_unitOfWork!.GetRepository<T>().Context); // 不带作用域
    }

    public void Dispose()
    {
        _unitOfWork?.Dispose();
    }

    /// <summary>
    /// 仓储对象包装器。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    sealed class SqlSugarRepositoryWrapper<T> : SimpleClient<T>, IRepository<T> 
        where T : class, IEntity, new()
    {
        public SqlSugarRepositoryWrapper(ISqlSugarClient context) : base(context)
        {
        }
    }
}
